package sax;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

public class PersonHandler implements ContentHandler
{

	private ArrayList<Person> tutti = new ArrayList<Person>();
	private String currentValue;
	private Person person;

	public void characters(char[] ch, int start, int length) throws SAXException
	{
		currentValue = new String(ch, start, length);
	}

	public void startElement(String uri, String localName, String qName, Attributes atts)
			throws SAXException
	{
		if (localName.equals("person"))
		{
			person = new Person();

			person.setId(Integer.parseInt(atts.getValue("id")));
		}
	}

	public void endElement(String uri, String localName, String qName) throws SAXException
	{

		if (localName.equals("nome"))
		{
			person.setNome(currentValue);
		}

		if (localName.equals("cognome"))
		{
			person.setCognome(currentValue);
		}

		if (localName.equals("data"))
		{
			SimpleDateFormat datumsformat = new SimpleDateFormat("dd.MM.yyyy");
			try
			{
				Date date = datumsformat.parse(currentValue);
				person.setData(date);
			}
			catch (ParseException e)
			{
				e.printStackTrace();
			}
		}

		if (localName.equals("cap"))
		{
			person.setCap(currentValue);
		}

		if (localName.equals("citta"))
		{
			person.setCitta(currentValue);
		}

		if (localName.equals("person"))
		{
			tutti.add(person);
		}
	}

	public void endDocument() throws SAXException
	{
	}

	public void endPrefixMapping(String prefix) throws SAXException
	{
	}

	public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException
	{
	}

	public void processingInstruction(String target, String data) throws SAXException
	{
	}

	public void setDocumentLocator(Locator locator)
	{
	}

	public void skippedEntity(String name) throws SAXException
	{
	}

	public void startDocument() throws SAXException
	{
	}

	public void startPrefixMapping(String prefix, String uri) throws SAXException
	{
	}
	
	public ArrayList<Person> getTutti(){
		return tutti;
	}
}
